﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace WindowsFormsApplication3
{
    public class StringProcess
    {
        #region 获得某个字符串在另个字符串中出现的次数【GetStrCount(string strOriginal,string strSymbol)】

        ///<summary>
        /// 函数功能：获得某个字符串在另个字符串中出现的次数
        /// 函数名称：GetStrCount(string strOriginal,string strSymbol)
        /// 参    数：strOriginal 要处理的字符,string 类型
        /// 参    数：strSymbol 符号,string 类型
        /// 返 回 值：nCount 出现的次数,int 类型
        /// 调用模块：
        /// 程 序 员：林冬武
        /// 编制日期：2005-03-24
        /// 修 改 人：
        /// 修改日期：
        /// 函数说明：
        /// 版    本：Ver1.0
        /// </summary>
        public static int GetStrCount(string strOriginal, string strSymbol)
        {
            int nCount = 0;
            for (int i = 0; i < (strOriginal.Length - strSymbol.Length + 1); i++)
            {
                if (strOriginal.Substring(i, strSymbol.Length) == strSymbol)
                {
                    nCount = nCount + 1;
                }
            }
            return nCount;
        }

        #endregion

        #region 获得某个字符串在另个字符串第一次出现时前面所有字符【GetFirstStr(string strOriginal,string strSymbol)】

        ///<summary>
        /// 函数功能：获得某个字符串在另个字符串第一次出现时前面所有字符
        /// 函数名称：GetFirstStr(string strOriginal,string strSymbol)
        /// 参    数：strOriginal 要处理的字符,string 类型
        /// 参    数：strSymbol 符号,string 类型
        /// 返 回 值：string 类型
        /// 调用模块：
        /// 程 序 员：林冬武
        /// 编制日期：2005-03-24
        /// 修 改 人：
        /// 修改日期：
        /// 函数说明：
        /// 版    本：Ver1.0
        /// </summary>
        public static string GetFirstStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.IndexOf(strSymbol);
            if (strPlace != -1)
                strOriginal = strOriginal.Substring(0, strPlace);
            return strOriginal;
        }

        #endregion

        #region 获得某个字符串在另个字符串最后一次出现时后面所有字符【GetLastStr(string strOriginal,string strSymbol)】

        ///<summary>
        /// 函数功能：获得某个字符串在另个字符串最后一次出现时后面所有字符
        /// 函数名称：GetLastStr(string strOriginal,string strSymbol)
        /// 参    数：strOriginal 要处理的字符,string 类型
        /// 参    数：strSymbol 符号,string 类型
        /// 返 回 值：string 类型
        /// 调用模块：
        /// 程 序 员：林冬武
        /// 编制日期：2005-03-24
        /// 修 改 人：
        /// 修改日期：
        /// 函数说明：
        /// 版    本：Ver1.0
        /// </summary>
        public static string GetLastStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.LastIndexOf(strSymbol) + strSymbol.Length;
            strOriginal = strOriginal.Substring(strPlace);
            return strOriginal;
        }

        #endregion

        #region 获得两个字符之间第一次出现时前面所有字符【GetTwoMiddleFirstStr(string strOriginal,string strFirst,string strLast)】

        ///<summary>
        /// 函数功能：获得两个字符之间第一次出现时前面所有字符
        /// 函数名称：GetTwoMiddleFirstStr(string strOriginal,string strFirst,string strLast)
        /// 参    数：strOriginal 要处理的字符,string 类型
        /// 参    数：strFirst 最前哪个字符,string 类型
        /// 参    数：strLast 最后哪个字符,string 类型
        /// 返 回 值：string 类型
        /// 调用模块：
        /// 程 序 员：林冬武
        /// 编制日期：2005-03-24
        /// 修 改 人：
        /// 修改日期：
        /// 函数说明：
        /// 版    本：Ver1.0
        /// </summary>
        public static string GetTwoMiddleFirstStr(string strOriginal, string strFirst, string strLast)
        {
            strOriginal = GetFirstStr(strOriginal, strLast);
            strOriginal = GetLastStr(strOriginal, strFirst);
            return strOriginal;
        }

        #endregion

        #region 字符串置空 【SetNull(string str)】 

        /// <summary>
        /// 字符串置空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SetNull(string str)
        {
            if (str.Trim() == "" || str.Trim() == ".")
            {
                str = "null";
            }
            return str;
        }

        #endregion

        #region 字符串置空 【SetDBNull(string str, DataRow dr, int iIndex)】 

        /// <summary>
        /// 字符串置空
        /// </summary>
        /// <param name="str"></param>
        /// <param name="dr"></param>
        /// <param name="iIndex"></param>
        public static void SetDBNull(string str, DataRow dr, int iIndex)
        {
            if (str == "null")
            {
                dr[iIndex] = DBNull.Value;
            }
            else
            {
                dr[iIndex] = str;
            }
        }

        #endregion

        #region 字符串置空 【SetDBNull(string str, DataRow dr, string Column)】 

        /// <summary>
        /// 字符串置空
        /// </summary>
        /// <param name="str"></param>
        /// <param name="dr"></param>
        /// <param name="Column"></param>
        public static void SetDBNull(string str, DataRow dr, string Column)
        {
            if (str == "null")
            {
                dr[Column] = DBNull.Value;
            }
            else
            {
                dr[Column] = str;
            }
        }

        #endregion

        #region 获得数组的值 【 GetArryValue(string[] sArry, int iIndex)】 

        public static string GetArryValue(string[] sArry, int iIndex)
        {
            string sResult = "";
            if (iIndex >= 0 && iIndex < sArry.Length)
            {
                sResult = sArry[iIndex];
            }
            return sResult;
        }

        #endregion

        #region 数据高低位转换 【HiToDi(string strData)】

        /// <summary>
        /// 数据高低位转换
        /// </summary>
        public static string HiToDi(string strData)
        {
            int iLength = strData.Length;
            int i = 0;
            StringBuilder builder = new StringBuilder();

            for (i = 2; i <= iLength; i += 2)
            {
                builder.Append(strData.Substring(iLength - i, 2));
            }

            return builder.ToString();
        }

        #endregion

        #region 把字节型转换成十六进制字符串【ByteToString(byte[] InBytes)】

        /// <summary>
        /// 把字节型转换成十六进制字符串
        /// </summary>
        /// <param name="InBytes"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] InBytes)
        {
            StringBuilder StringOut = new StringBuilder();

            foreach (byte InByte in InBytes)
            {
                StringOut.Append(String.Format("{0:X2} ", InByte));
            }

            return StringOut.ToString();
        }

        #endregion

        #region 把十六进制字符串转换成字节型【StringToByte(string InString)】

        /// <summary>
        ///把十六进制字符串转换成字节型(字符必须用" "隔开)
        ///举例:"11 22 33 44" ==>0B16212C
        /// </summary>
        /// <param name="InString"></param>
        /// <returns></returns>
        public static byte[] StringToByte(string InString)
        {
            string[] ByteStrings;
            ByteStrings = InString.Split(" ".ToCharArray());  //按跳过空格截取
            int nLength = ByteStrings.Length - 1;
            byte[] ByteOut;
            ByteOut = new byte[nLength];
            for (int i = 0; i < nLength; i++)
            {
                ByteOut[i] = Convert.ToByte(ByteStrings[i], 16);
            }
            return ByteOut;
        }

        #endregion

        #region 从包含中英文的字符串中截取固定长度的一段【cutString(string strInput,int intLen)】

        ///	<summary>
        /// 从包含中英文的字符串中截取固定长度的一段，strInput为传入字符串，intLen为截取长度（一个汉字占两个位）,strOutPut 剩余字符。
        /// </summary>
        public static string cutString(string strInput, int intLen, ref string strOutPut)
        {
            StringBuilder builder = new StringBuilder();
            strInput = strInput.Trim();
            byte[] myByte = System.Text.Encoding.Default.GetBytes(strInput);
            if (myByte.Length > intLen)
            {
                //截取操作
                string resultStr = "";
                for (int i = 0; i < strInput.Length; i++)
                {
                    byte[] tempByte = System.Text.Encoding.Default.GetBytes(resultStr);
                    byte[] tempByte1 = System.Text.Encoding.Default.GetBytes(strInput.Substring(i, 1));

                    if (tempByte.Length + tempByte1.Length <= intLen)
                    {
                        builder.Append(strInput.Substring(i, 1));
                        resultStr = builder.ToString();
                    }
                    else
                    {
                        if (i < strInput.Length)
                        {
                            strOutPut = strInput.Substring(i, strInput.Length - i);
                        }

                        break;
                    }
                }

                return resultStr;
            }
            else
            {
                return strInput;
            }
        }

        #endregion

        #region 短信内容编码【smsPDUEncoded(string srvContent)】

        /// <summary>
        /// 函数功能：短信内容编码
        /// 函数名称：smsPDUEncoded(string srvContent)
        /// 参    数：srvContent 要进行转换的短信内容,string类型
        /// 返 回 值：编码后的短信内容，string类型
        /// 程 序 员：lindongwu@163.net
        /// 编制日期：2005-07-15
        /// 函数说明：
        ///          1，采用Big-Endian 字节顺序的 Unicode 格式编码，也就说把高低位的互换在这里完成了
        ///          2，将转换后的短信内容存进字节数组
        ///          3，去掉在进行Unicode格式编码中，两个字节中的"-",例如：00-21，变成0021
        ///          4，将整条短信内容的长度除2，保留两位16进制数(通讯组件处理了)
        /// </summary>
        public static string smsPDUEncoded(string strvContent)
        {
            StringBuilder builder = new StringBuilder();

            Encoding encodingUTF = System.Text.Encoding.BigEndianUnicode;
            string strReturn = null;
            byte[] encodedBytes = encodingUTF.GetBytes(strvContent);
            for (int i = 0; i < encodedBytes.Length; i++)
            {
                builder.Append(BitConverter.ToString(encodedBytes, i, 1));
            }
            strReturn = builder.ToString();

            //			strReturn = String.Format("{0:X2}{1}",strReturn.Length / 2,strReturn);

            return strReturn;
        }

        #endregion

        #region 字符串加1[AddString(string strAddString)]

        public static string AddString(string strAddString)
        {
            try
            {
                bool bAdd = true;
                int iStringLength = strAddString.Length;
                int iLastString;
                string strLastString = "";
                char charLastChar;

                for (int i = iStringLength; i > 0; i--)
                {
                    strLastString = strAddString.Substring(i - 1, 1);
                    charLastChar = Convert.ToChar(strLastString);
                    if (bAdd)
                    {
                        //是否是数字
                        if (charLastChar >= Convert.ToChar("0") && charLastChar <= Convert.ToChar("9"))
                        {
                            if (strLastString == "9")
                            {
                                strLastString = "0";
                                bAdd = true;
                            }
                            else
                            {
                                iLastString = Convert.ToInt32(strLastString) + 1;
                                strLastString = iLastString.ToString();
                                bAdd = false;
                            }
                        }
                        else if (Convert.ToChar(strLastString.ToUpper()) >= Convert.ToChar("A") && Convert.ToChar(strLastString.ToUpper()) <= Convert.ToChar("Z"))
                        {
                            //字符
                            if (strLastString == "Z")
                            {
                                strLastString = "A";
                                bAdd = true;
                            }
                            else if (strLastString == "z")
                            {
                                strLastString = "a";
                                bAdd = true;
                            }
                            else
                            {
                                strLastString = Convert.ToChar(Convert.ToInt32(charLastChar) + 1).ToString();
                                bAdd = false;
                            }
                        }

                        strAddString = strAddString.Substring(0, i - 1) + strLastString + strAddString.Substring(i, iStringLength - i);
                    }
                    else
                    {
                        break;
                    }
                }
                return strAddString;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }
        #endregion

        #region 字符转Ascill [string StrToAscill(string strData)]
        public static string StrToAscillX2(string strData, int iDataLen)
        {
            string RetAscillData = "";
            for (int i = 0; i < strData.ToString().Length; i++)
            {
                int iAscill = Convert.ToChar(strData.Substring(i, 1));
                RetAscillData = RetAscillData + iAscill.ToString("X2");
            }
            int iNulLen = iDataLen - strData.Length;
            //			string strTemp = iNulLen != 0 ? Convert.ToString("0").PadRight(iNulLen * 2,'0') : "";
            RetAscillData = RetAscillData.PadRight(iDataLen * 2, '0');
            return RetAscillData;
        }
        #endregion

        #region Ascill转字符串 [AscillDataToStr(string strAscillData)]
        public static string AscillDataToStr(string strAscillData)
        {
            string strRetData = "";
            for (int n = 0; n < strAscillData.Length / 2; n++)
            {
                char c = (char)Convert.ToInt32(strAscillData.Substring(2 * n, 2), 16);
                strRetData = strRetData + c.ToString();
            }
            return strRetData.Replace("\0", " ");
        }
        #endregion

        #region 置空格
        /// <summary>
        /// 置空格
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static string SpaceFarme(string strData)
        {
            string strRetString = "";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            strData = strData.Replace(" ", "");
            int iLen = strData.Length / 2;
            for (int i = 0; i < iLen; i++)
            {
                sb.Append(strData.Substring(i * 2, 2) + " ");
            }
            return strRetString = sb.ToString();
        }

        #endregion

        #region 减33 处理
        public static string Remove0x33(string strData)
        {
            //数据域 - 33
            System.Text.StringBuilder sbRetData = new StringBuilder();
            int iLen = strData.Length;
            for (int i = 0; i < iLen; i += 2)
            {
                int iniTemp = Convert.ToInt32(strData.Substring(i, 2), 16);
                iniTemp = iniTemp < 0x33 ? iniTemp + 256 : iniTemp;
                iniTemp = iniTemp - 0x33;
                sbRetData.Append(iniTemp.ToString("X2"));
            }
            return sbRetData.ToString();
        }
        #endregion

        #region 加0x33处理
        public static string Add0x33(string strData)
        {
            //数据域 - 33
            System.Text.StringBuilder sbRetData = new StringBuilder();
            int iLen = strData.Length;
            for (int i = 0; i < iLen; i += 2)
            {
                int iniTemp = Convert.ToInt32(strData.Substring(i, 2), 16);
                iniTemp = iniTemp + 0x33;
                iniTemp = iniTemp % 256;
                sbRetData.Append(iniTemp.ToString("X2"));
            }
            return sbRetData.ToString();
        }
        #endregion

        #region 字节字符串增加空格[string BytStringInsertSpace(string strString)]
        /// <summary>
        /// 字节字符串增加空格
        /// </summary>
        /// <param name="strString"></param>
        /// <returns></returns>
        public static string BytStringInsertSpace(string strString)
        {
            int iLen = strString.Length;

            StringBuilder sbData = new StringBuilder();

            for (int i = 0; i < iLen; i += 2)
            {
                sbData.Append(strString.Substring(i, 2) + " ");
            }

            string strTemp = sbData.ToString();

            return strTemp;
        }

        #endregion

        static public string GetNowTime()
        {
            DateTime re = DateTime.Now;
            string strSecond = DateTime.Now.Second.ToString();
            if (strSecond.Length == 1)
            {
                strSecond = "0" + strSecond;
            }
            string strMinute = DateTime.Now.Minute.ToString();
            if (strMinute.Length == 1)
            {
                strMinute = "0" + strMinute;
            }
            string strHour = DateTime.Now.Hour.ToString();
            if (strHour.Length == 1)
            {
                strHour = "0" + strHour;
            }
            string strDay = DateTime.Now.Day.ToString();
            if (strDay.Length == 1)
            {
                strDay = "0" + strDay;
            }

            string strMonth = DateTime.Now.Month.ToString();
            if (strMonth.Length == 1)
            {
                strMonth = "0" + strMonth;
            }
            string strYear = DateTime.Now.Year.ToString();
            string strtime = "[" + strYear + "-" + strMonth + "-" + strDay + " " + strHour + ":" + strMinute + ":" + strSecond + "]";
            return (strtime);
        }


        public void strHexToInt()   //"14F4" ==>5199
        {
            string strHex = "14F4";
            int iDec = Convert.ToInt32(strHex, 16);
        }


        #region 整理数据格式
        public static string DataFormat(string sData, int count)
        {
            while (sData.Length < count)
            {
                sData = "0" + sData;
            }
            string re = "";
            for (int i = 0; i < sData.Length; i++)
            {
                re += sData.Substring(sData.Length - i - 2, 2);
                i++;
            }
            return re;
        }
        #endregion

        #region
        public static string FloatToStrHex(float fValue)
        {
            string strHex;
            float F = 27.251F;
            byte[] a;
            a = BitConverter.GetBytes(F);
            strHex = BitConverter.ToString(a);
            strHex = strHex.Replace("-", "");
            strHex = DataFormat(strHex, strHex.Length);
            return (strHex);
        }
        #endregion


        #region
        public static float StrHexToFloat(string strHex)
        {
            byte[] arr = new byte[strHex.Length / 2];
            for (int i = strHex.Length / 2; i > 0 ; i--)
            {
                arr[i-1] = Convert.ToByte(strHex.Substring((i-1) * 2, 2), 16);
            }
            float f1 = BitConverter.ToSingle(arr, 0);
            return (f1);
        }
        #endregion


        //加入小数点 dot_num：小数点位数 strData原始数据
        public static string PrintDigitalText(string strData, int dot_num)
        {
            int i;
            string strDecimal;   //小数部分
            string strInterger;  //整数部分
            string strValueText; 
            strInterger = strData.Substring(0, strData.Length - dot_num);
            strDecimal  = strData.Substring(strData.Length- dot_num, dot_num);
            for(i = 0; i < strInterger.Length -1; i++)
            {
                if (strInterger.Substring(i, 1) != "0") break;  //整数部分灭0处理
            }
            strInterger = strInterger.Substring(i, strInterger.Length - i);

            strValueText = strInterger + "." + strDecimal;      //没
            return (strValueText);
        }


        public static string PrintDigitalText(string strData, int dot_num, string strSign)
        {
            int i;
            string strDecimal;   //小数部分
            string strInterger;  //整数部分
            string strValueText;
            string strS = "";

            if (strSign == "sign")
            {
                string strMsg = strData.Substring(0, 1);
                if (strMsg == "8") 
                {
                    strMsg = "0";
                    strData = strMsg + strData.Substring(1, strData.Length - 1);
                    strS = "-";
                }
            }

            strInterger = strData.Substring(0, strData.Length - dot_num);
            strDecimal = strData.Substring(strData.Length - dot_num, dot_num);
            for (i = 0; i < strInterger.Length - 1; i++)
            {
                if (strInterger.Substring(i, 1) != "0") break;  //整数部分灭0处理
            }
            strInterger = strInterger.Substring(i, strInterger.Length - i);

            strValueText = strS + strInterger + "." + strDecimal;
            return (strValueText);
        }

    }
}
